package com.mk.wardsystemserver.service.impl;

import com.mk.wardsystemserver.AdminUtils;
import com.mk.wardsystemserver.pojo.Admin;
import com.mk.wardsystemserver.pojo.Menu;
import com.mk.wardsystemserver.mapper.MenuMapper;
import com.mk.wardsystemserver.service.IMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zhoubin
 * @since 2022-02-24
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 根据用户id查询菜单列表
     *
     * @return
     */
    @Override
    //如果要修改数据库的数据首先要把redis中的数据清空，如果不清空的话，那么后端查询一直都是redis中的旧数据，
    // 应该去数据库查找最新的数据放在redis中
    public List<Menu> getMenusByAdminId() {
        Integer adminId = ((Admin) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId();
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        // 从redis获取菜单数据
        List<Menu> menus = (List<Menu>) valueOperations.get("menu_"+adminId);
        // 如果redis获取的值为空 就去数据库获取
        if(CollectionUtils.isEmpty(menus)){
            menus = menuMapper.getMenusByAdminId(adminId);
            // 将数据设置到Redis中
            valueOperations.set("menu_"+adminId,menus);
        }
        return menus;
//        Integer adminId = AdminUtils.getCurrentAdmin().getId();
//        List<Menu> menus = menuMapper.getMenusByAdminId(adminId);
//        return menus;
    }

    /**
     * 根据角色获取菜单列表
     * @return
     */
    @Override
    public List<Menu> getMenusWithRole() {

        return menuMapper.getMenusWithRole();
    }

    /**
     * 查询所有菜单
     * @return
     */
    @Override
    public List<Menu> getAllMenus() {
        return menuMapper.getAllMenus();
    }
}
